package com.match.competition_sub.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.match.competition_sub.entity.Student;
import com.match.competition_sub.excel.StudentData;
import com.match.competition_sub.service.StudentService;
import com.match.servicebase.exceptionhandler.AdiosException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;


public class StudentExcelListener extends AnalysisEventListener<StudentData> {

    //因为SubjectExcelListener不交给spring进行管理，需要自己new，不能注入其他对象
    //不能实现数据库操作
    public StudentService studentService;
    public StudentExcelListener() {}
    public StudentExcelListener(StudentService studentService) {
        this.studentService = studentService;
    }

    //读取excel内容，一行一行进行读取
    @Override
    public void invoke(StudentData studentData, AnalysisContext analysisContext) {
        if(studentData == null) {
            throw new AdiosException(20001,"文件数据为空");
        }

        //判断学号是否存在
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        Student existOneSubject = this.existOneSubject(studentService, studentData.getNumber());
        if(existOneSubject == null) {
            //没有相同的学号，进行添加
            existOneSubject = new Student();
            existOneSubject.setNumber(studentData.getNumber());
            existOneSubject.setPassword(passwordEncoder.encode(studentData.getPassword()));
            existOneSubject.setName(studentData.getName());
            existOneSubject.setSex(studentData.getSex());
            existOneSubject.setLever(studentData.getLever());
            existOneSubject.setGrade(studentData.getGrade());
            existOneSubject.setMajorNum(studentData.getMajorNum());
            existOneSubject.setMajorNam(studentData.getMajorNam());
            existOneSubject.setClassNam(studentData.getClassNam());
            existOneSubject.setRole("学生");
            existOneSubject.setAvatar("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F202004%2F11%2F20200411200644_fyukv.jpg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1651022198&t=26811c4bb62fbad766c6c2230176488e");
            studentService.save(existOneSubject);
        }

    }
    //判断一级分类不能重复添加
    private Student existOneSubject(StudentService studentService,String number) {
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        wrapper.eq("number",number);
        Student student = studentService.getOne(wrapper);
        return student;
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
